package com.leyou.item.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import com.leyou.item.service.BrandService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class BrandServiceImpl implements BrandService{

    @Autowired
    private BrandMapper brandMapper;

    /**
     * 根据查询数据 进行分页 并排序 查看商品详情信息
     * @param key
     * @param page
     * @param rows
     * @param sorBy
     * @param desc
     * @return
     */
    @Override
    public PageResult<Brand> queryBrandByPage(String key, Integer page, Integer rows, String sorBy, Boolean desc) {

        //创建example实例化对象
        Example example = new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria();

        //根据name 模糊查询 或者 根据首字母进行模糊查询
        if (StringUtils.isNotBlank(key)) {
           criteria.andEqualTo("name", key).orEqualTo("letter",key);
        }
        //添加分页条件
        PageHelper.startPage(page, rows);
        //添加排序条件
        example.setOrderByClause(sorBy+" "+(desc?"desc":"asc"));

        List<Brand> brands = brandMapper.selectByExample(example);
        //包装成分页结果集
        PageInfo pageInfo = new PageInfo(brands);
        return new PageResult<Brand>(pageInfo.getTotal(),pageInfo.getList());
    }

    /**
     * 新增商品
     * @param brand
     * @param cids
     */
    @Transactional
    @Override
    public void saveBrand(Brand brand, List<Long> cids) {
        // 新增品牌，主键回写
        boolean flag = brandMapper.insertSelective(brand) == 1;

        //新增中间表
        if (flag) {
            cids.forEach(cid->{brandMapper.insertBrandAndCategory(cid,brand.getId());});
        }
    }

    @Override
    public List<Brand> queryBrandsByCid(Long cid) {

        return brandMapper.selectBrandById(cid);
    }

    /**
     * 根据 id 查询 商品
     * @param id
     * @return
     */
    @Override
    public Brand queryBrandById(Long id) {
        return brandMapper.selectByPrimaryKey(id);
    }
}
